package com.wordsay.parser.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStreamReader;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.wordsay.common.Constant;
import com.wordsay.entity.Group;
import com.wordsay.entity.GroupDialog;
import com.wordsay.entity.Talk;
import com.wordsay.parser.ChatParser;
import com.wordsay.util.TalkUtil;

public class FxGroupChatParser implements ChatParser {

	private static Logger log = LogManager.getLogger(FxGroupChatParser.class.getName());
			
	@Override
	public Object parse(String chatFilePath) throws Exception {
		
		log.info("start parse chat file ["+chatFilePath+"] in FxGroup chat parser");

		File chatFile = new File(chatFilePath);
		
		BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(chatFilePath),"utf-8"));
		
		String line = null;
		GroupDialog dialog = new GroupDialog();
		
		String fileName = chatFile.getName();
		Group group = new Group();
		group.setDiscussion(fileName.contains("DG") ? true : false);
		group.setId(TalkUtil.parseTalkId(fileName, fileName.contains("DG") ? Constant.DISCUSSION_TALK : Constant.GROUP_TALK));
		group.setName(fileName.substring(0,fileName.indexOf("(")));
		
		while((line = reader.readLine()) != null) {
			
			if(TalkUtil.isFxNewTalk(line)){
			 
				Talk talk = TalkUtil.parseFxMessage(line);
				if(talk == null){
					continue;
				}
				dialog.getTalks().add(talk);
				
				if(!group.getMembers().containsKey(talk.getSpeaker().getName())){
					group.getMembers().put(talk.getSpeaker().getName(), talk.getSpeaker());
				}
				
			} else {
			
				if(dialog.getLastTalk() == null){
					continue;
				}
				dialog.getLastTalk().appendMessage(line);
			}
			
		}
		
		dialog.setGroup(group);
		
		return dialog;
	}
}
